import os
from PIL import Image
from datetime import datetime


def compress_image(input_path, max_size_mb=1):
    """压缩图片到指定大小"""
    img = Image.open(input_path)

    # 初始质量
    quality = 95
    max_size_bytes = max_size_mb * 1024 * 1024

    while True:
        # 保存临时文件
        temp_path = f"{input_path}.temp"
        img.save(temp_path, quality=quality, optimize=True)

        # 检查文件大小
        if os.path.getsize(temp_path) <= max_size_bytes:
            # 如果大小合适，替换原文件
            os.replace(temp_path, input_path)
            break

        # 删除临时文件
        os.remove(temp_path)

        # 降低质量继续尝试
        quality -= 5
        if quality < 5:
            # 如果质量太低，尝试调整图片尺寸
            width, height = img.size
            img = img.resize((int(width * 0.9), int(height * 0.9)), Image.LANCZOS)
            quality = 95
            continue


def generate_barcode(product_code):
    """生成产品条形码"""
    # 这里可以使用第三方库生成条形码
    # 例如：python-barcode
    pass


def format_date(date):
    """格式化日期"""
    if isinstance(date, str):
        date = datetime.strptime(date, "%Y-%m-%d")
    return date.strftime("%Y-%m-%d")


def validate_price(price):
    """验证价格格式"""
    try:
        price = float(price)
        if price < 0:
            return False
        return True
    except (ValueError, TypeError):
        return False


def validate_dimension(dimension):
    """验证尺寸格式（毫米）"""
    try:
        dimension = float(dimension)
        if dimension <= 0:
            return False
        return True
    except (ValueError, TypeError):
        return False
